import {magicURL} from '~/settings'

import getChatHubWithMagic from './GetSet'
import {allowedMessageTypes, chatTypes, generateMessages, getPreviousMessages, sliceIds, source} from "./optionsSets";
import axios from "axios";



let expUrl = new RegExp('^(https?://)([-a-zA-z0-9]+\\.)+([-a-zA-z0-9]+)+\\S*$');

function getUuidNojian() {
    return URL.createObjectURL(new Blob()).split('/')[3].replace(/-/g, '');
}


class SendMessageManager {
    invocationId: any
    conversationId: any
    clientId: any
    conversationSignature: any
    optionsSets: any
    //(string,string,string,boolena)
    //(会话id，客户端id，签名id，是否是开始)
    constructor(conversationId: any, clientId: any, conversationSignature: any, invocationId: any) {
        this.invocationId = invocationId == undefined ? 1 : invocationId;
        this.conversationId = conversationId;
        this.clientId = clientId;
        this.conversationSignature = conversationSignature;
        this.optionsSets = 'balance';
    }

    //chatTypes中的一种
    setChatType(chatType: any) {
        this.optionsSets = chatType;
    }

    //发送json数据
    async sendJson(chatWebSocket: any, json: any) {
        let go = JSON.stringify(json) + '\u001e';
        await chatWebSocket.send(go);
        // console.log('发送', go)
    }

    //获取用于发送的握手数据
    //(WebSocket)
    async sendShakeHandsJson(chatWebSocket: any) {
        await this.sendJson(chatWebSocket, {
            "protocol": "json",
            "version": 1
        });
    }

    //获取用于发送的聊天数据
    //(WebSocket,sreing)
    async sendChatMessage(chatWebSocket: any, chat: any) {
        //@ts-ignore
        let optionsSets = chatTypes[this.optionsSets];
        if (!optionsSets) {
            optionsSets = chatTypes.balance;
            console.warn("不存在的ChatType", this.optionsSets);
            return;
        }

        let json = {
            "arguments": [{
                "source": source,
                "optionsSets": optionsSets,
                "allowedMessageTypes": allowedMessageTypes,
                "sliceIds": sliceIds,
                "verbosity": "verbose",
                "traceId": getUuidNojian(),
                "isStartOfSession": (this.invocationId <= 1) ? true : false,
                "message": await generateMessages(this, chat),
                "conversationSignature": this.conversationSignature,
                "participant": {
                    "id": this.clientId
                },
                "conversationId": this.conversationId,
                "previousMessages": (this.invocationId <= 1) ? await getPreviousMessages() : undefined
            }],
            "invocationId": this.invocationId.toString(),
            "target": "chat",
            "type": 4
        };
        await this.sendJson(chatWebSocket, json);
        this.invocationId++;
    }
}


//处理返回消息的类
class ReturnMessage {
    catWebSocket: any
    onMessage: any

    //(WebSocket,function:可以不传)
    constructor(catWebSocket: any, lisin: any) {
        this.catWebSocket = catWebSocket;
        this.onMessage = [() => {
            //console.log(JSON.stringify(v))
        }];
        if ((typeof lisin) == 'function') {
            this.regOnMessage(lisin);
        }
        catWebSocket.onmessage = (mess: any) => {
            //console.log('收到', mess.data);
            let sss = mess.data.split('\u001e');
            for (let i = 0; i < sss.length; i++) {
                if (sss[i] == '') {
                    continue;
                }
                for (let j in this.onMessage) {
                    if ((typeof this.onMessage[j]) == 'function') {
                        try {
                            this.onMessage[j](JSON.parse(sss[i]), this);
                        } catch (e:any) {
                            console.warn(e)
                        }
                    }
                }
            }
        }
        catWebSocket.onclose = () => {
            for (let i in this.onMessage) {
                if ((typeof this.onMessage[i]) == 'function') {
                    try {
                        this.onMessage[i]({
                            type: 'close',
                            mess: '连接关闭'
                        }, this);
                    } catch (e) {
                        console.warn(e)
                    }
                }
            }
        }
        catWebSocket.onerror = (mess: any) => {
            // console.log(mess);
            for (let i in this.onMessage) {
                if ((typeof this.onMessage[i]) == 'function') {
                    try {
                        this.onMessage[i]({
                            type: 'error',
                            mess: mess
                        }, this);
                    } catch (e) {
                        console.warn(e)
                    }
                }
            }
        }
    }

    /*
    获取消息WebSocket
    */
    getCatWebSocket() {
        return this.catWebSocket;
    }

    /**
     * 注册收到消息监听器
     */
    //(function(json,ReturnMessage))
    regOnMessage(theFun: any) {
        this.onMessage[this.onMessage.length] = theFun;
    }
}

//处理聊天的类
export class Chat {
    sendMessageManager: any
    //theChatType chatTypes变量中的其中一个
    //invocationId 可以不传
    //(string,ture|false|'repeat',string,string,string,theChatType,int|undefined)
    constructor(charID: any, clientId: any, conversationSignature: any, theChatType: any, invocationId = undefined) {
        this.sendMessageManager = new SendMessageManager(charID, clientId, conversationSignature, invocationId);
        if (theChatType) {
            this.sendMessageManager.setChatType(theChatType);
        }
    }

    /**
     * 返回
     {
		 ok:true|false，
		 message:显示消息，
		 obj:ReturnMessage对象
	   }
     当ok等于false时，不返回ReturnMessage
     * 参数 消息string,当收到消息的函数,当关闭时函数
     */
    //(string,function:可以不传)
    async sendMessage(message: any, onMessage: any) {
        try {
            let restsrstUrl = 'wss://sydney.bing.com/sydney/ChatHub';
            let chatWithMagic = await getChatHubWithMagic()
            if (chatWithMagic) {
                let magicUrl = magicURL
                if (!expUrl.test(magicUrl)) {
                    return {
                        ok: false,
                        message: "魔法链接不正确！请修改魔法链接。"
                    };
                }
                restsrstUrl = URLTrue(magicUrl.replace('http', 'ws'), "sydney/ChatHub");
            }
            let chatWebSocket = new WebSocket(restsrstUrl);
            chatWebSocket.onopen = () => {
                this.sendMessageManager.sendShakeHandsJson(chatWebSocket);
                this.sendMessageManager.sendChatMessage(chatWebSocket, message);
            }
            return {
                ok: true,
                message: 'ok',
                obj: new ReturnMessage(chatWebSocket, onMessage),
                chatWithMagic: chatWithMagic
            };
        } catch (e: any) {
            console.warn(e)
            return {
                ok: false,
                message: "发生错误,可能是网络连接错误:" + e.message
            };
        }
    }
}

// async function copyCookies() {
//     let tmp = "ajs_anonymous_id=4dbed465-09c9-4e2f-ba26-91c284f8feb6;ajs_user_id=dec02fa1-a6b9-45f1-83a5-1211e295ff45;__stripe_mid=13da4ced-8382-4be2-8c05-8d3393690b6de19909; SRM_B=076C63F7AACA60CE160F7194ABE46146; EDGSRVCPERSIST=discoverl1=firsttimeinuds=1; SRA_B=2F6D717519E26D896ECC6D65FFFFFFFF; MR=0; SRM_M=076C63F7AACA60CE160F7194ABE46146; SRA_M=2F6D717519E26D896ECC6D65FFFFFFFF; SRM_I=076C63F7AACA60CE160F7194ABE46146; SRA_I=2F6D717519E26D896ECC6D65FFFFFFFF; MUID=0ECD4BAD70ED648907E5595671696568; _EDGE_S=F=1&SID=3B379CD3A1FE64D2357A8E28A07A6576&mkt=zh-CN; _EDGE_V=1; SRCHD=AF=NOFORM; SRCHUID=V=2&GUID=28C20762FB50407DACC54BEDC196FA6E&dmnchg=1; _UR=QS=0&TQS=0; MicrosoftApplicationsTelemetryDeviceId=477db27a-8b59-4069-a6a2-a17c59f97759; _HPVN=CS=eyJQbiI6eyJDbiI6MSwiU3QiOjAsIlFzIjowLCJQcm9kIjoiUCJ9LCJTYyI6eyJDbiI6MSwiU3QiOjAsIlFzIjowLCJQcm9kIjoiSCJ9LCJReiI6eyJDbiI6MSwiU3QiOjAsIlFzIjowLCJQcm9kIjoiVCJ9LCJBcCI6dHJ1ZSwiTXV0ZSI6dHJ1ZSwiTGFkIjoiMjAyMy0wNC0yMlQwMDowMDowMFoiLCJJb3RkIjowLCJHd2IiOjAsIkRmdCI6bnVsbCwiTXZzIjowLCJGbHQiOjAsIkltcCI6Mn0=; SNRHOP=I=&TS=; ai_session=DK+VYJ7Sqq8D+0CBrbQ1g/|1682170767023|1682170767023; SRCHS=PC=NMTS; _tarLang=default=zh-Hans; _TTSS_IN=hist=WyJlbiIsImF1dG8tZGV0ZWN0Il0=; _TTSS_OUT=hist=WyJ6aC1IYW5zIl0=; ANON=A=2F6D717519E26D896ECC6D65FFFFFFFF&E=1c3d&W=1; NAP=V=1.9&E=1be3&C=W9W3uuV-yvWSoLqwR6zN1r53ItvKO7wTN0QBWfQoa85Kgz8eN52obA&W=1; PPLState=1; KievRPSSecAuth=FABaBBRaTOJILtFsMkpLVWSG6AN6C/svRwNmAAAEgAAACJZm//mWd8I6GARJOb8JNMZFj6JxMKexoR3yL1WMCbzyVqTcJKjmTKrwNHVfVS0yxrhjFtI5F7AzycZpvPxs1QIVY2MlvPviZPrbF+X1iYriNoRDg1HjRaj2J4Nl5PTo9oJ0AGFDPl4C9ML21MgNgSBACUNNNArmo3dbCBvhFuyGPO+OZ0MGFMoJEZBXB0NHmVjHycWwSsTSfdYF1yavtLq9JoxNGwc0VlJaPdHGIhoNbXQB7R+asHJJUZ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EuO2WofBy7CmZCdggDNsWwCSAy+aC8ZeqKlcDz+OO8OorciMhtJb85pHyUG2gnL4kjJJpNObDy291490yLGYLIEqFABew81XPXcZPqohDo/sLE0LZFOHQw==; WLS=C=6c9352f044b5819c&N=炷俊; WLID=rWlgbo2nhael0c/p01YSCCmqrqdwo7jYzwyUERvxjUPC6vWXF9cXLH2c8F27Ehsvqfbd774myUD4qkguQ8WUjRT1tZ2J4nkvh6fzqMla7R4=; SUID=A; _hp2_id.3707852831={\"userId\":\"2986217153407084\",\"pageviewId\":\"5689315156689796\",\"sessionId\":\"772151508682587\",\"identity\":\"dec02fa1-a6b9-45f1-83a5-1211e295ff45\",\"trackerVersion\":\"4.0\",\"identityField\":null,\"isIdentified\":1}; USRLOC=HS=1&ELOC=LAT=30.533218383789062|LON=114.3879623413086|N=洪山区，湖北省|ELT=2|&CLOC=LAT=30.53321784616713|LON=114.38796363007671|A=733.4464586120832|TS=230423041758|SRC=W; _SS=SID=3B379CD3A1FE64D2357A8E28A07A6576&R=141&RB=141&GB=0&RG=0&RP=141&PC=NMTS; SRCHUSR=DOB=20230422&T=1682232347000&POEX=W; ipv6=hit=1682235951363&t=4; _U=1bojp-3kLYcjm3HecnhI92E-UTLBIBpBS1LB-EfI4cSh6VLQNm1dN-3Of2ByKJkkJEZV2jodCzdH0_0ZDaz7P8hXh8-SDtM5mZkXI0ieRuAcYCfa8LSWbY6WwjMPjNXiAW0hizBM_2na9VcSjyEuzdseSRw1tpMzP-Pi1D2vONLzR3wQkSFtLt5KtzuFSRIKWiEz3sCwXgkRl109n3Iq5aEOSTuVN-CBA7AFUItpwe_I; MUIDB=0ECD4BAD70ED648907E5595671696568; ABDEF=V=13&ABDV=11&MRNB=1682234854288&MRB=0; SRCHHPGUSR=SRCHLANG=zh-Hans&PV=15.0.0&BRW=XW&BRH=M&CW=1536&CH=797&SCW=1521&SCH=2773&DPR=1.0&UTC=480&DM=1&BZA=0&PRVCW=1536&PRVCH=797&EXLTT=31&WTS=63817768608&HV=1682234956; _RwBf=ilt=2&ihpd=1&ispd=1&rc=141&rb=141&gb=0&rg=0&pc=141&mtu=0&rbb=0.0&g=0&cid=&clo=0&v=4&l=2023-04-23T07:00:00.0000000Z&lft=0001-01-01T00:00:00.0000000&aof=0&o=0&p=bingcopilotwaitlist&c=MY00IA&t=1391&s=2023-04-18T23:57:20.9744733+00:00&ts=2023-04-23T07:29:15.4658640+00:00&rwred=0&wls=2&lka=0&lkt=0&TH=&mta=0&e=ZPpKrO5ygzDnX3X02luDOgEMIAcdnvVXnY9bteMijJkbNaahb1QyRB6MGgG6-9YqNkQfRr3uuhCSRn9LtPly2A&A=2F6D717519E26D896ECC6D65FFFFFFFF"
//     let s = tmp.split(" ");
//     for (let i = 0; i < s.length; i++) {
//         let t = s[i].split("=")
//         JsCookie.set(t[0],t[1])
//     }
// }

export const createChat = async (theChatType: any) => {
    let magicUrl = magicURL
    if (!magicUrl) {
        return {
            ok: false,
            message: "需要设置魔法链接才能聊天哦！"
        };
    }
    if (!expUrl.test(magicUrl)) {
        return {
            ok: false,
            message: "魔法链接不正确！请修改魔法链接。"
        };
    }
    try {
        // await copyCookies();
        let res = await axios.request({
            method: 'POST',
            url: '/newbingAPI/turing/conversation/create',
            withCredentials: true,
        })
        let rText = await res.data;
        if (rText.length < 1) {
            return {
                ok: false,
                message: "魔法似乎不能正常工作，试试换一个魔法链接？"
            };
        }
        let resjson = res.data
        if (!resjson.result) {
            console.warn(resjson);
            return {
                ok: false,
                message: "未知错误！"
            };
        }
        if (resjson.result.value != 'Success') {
            let type = resjson.result.value;
            let mess = resjson.result.message;
            if (resjson.result.value == 'UnauthorizedRequest') {
                type = 'NoLogin'
                mess = '首先你需要在bing登录微软账号！请前往 https://cn.bing.com/ 登录微软账号。';
            } else if (resjson.result.value == 'Forbidden') {
                type = 'NoPower'
                mess = '你还没有获得NewBing的使用权限';
            }
            console.warn(resjson);
            return {
                ok: false,
                type: type,
                message: mess
            };
        }
        return {
            ok: true,
            message: 'ok',
            obj: new Chat(resjson.conversationId, resjson.clientId, resjson.conversationSignature, theChatType)
        };
    } catch (e: any) {
        console.warn(e);
        return {
            ok: false,
            message: "发生错误,可能是魔法链接无法链接:" + e.message
        };
    }

}


/***
 * 补齐url
 */
function URLTrue(magicUrl: any, thiePath: any) {
    let url = magicUrl;
    if (!url.endsWith('/')) {
        url = url + '/';
    }
    url = url + thiePath;
    return url;
}